﻿using B.Rabbit.DataBase.Domain;
using B.Rabbit.DataBase.ErrorCode;
using B.Rabbit.DataBase.Infrastructure.Infrastructure;
using B.Rabbit.DataBase.Read.Api.Applocation.Command.Rabbit.Traceab;
using B.Rabbit.DataBase.Read.Api.DTOs;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.Rabbit.DataBase.Read.Api.Applocation.Handler.Rabbit.Traceab
{
    public class GetTraceabCommandHandler : IRequestHandler<GetTraceabCommand, ApiPaging<GetTraceabDTOs>>
    {
        IBaseRepository<TraceabilityModel> traceabmodel;

        public GetTraceabCommandHandler(IBaseRepository<TraceabilityModel> traceabmodel)
        {
            this.traceabmodel = traceabmodel;
        }
        /// <summary>
        /// 溯源信息列表展示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiPaging<GetTraceabDTOs>> Handle(GetTraceabCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<GetTraceabDTOs> res = new ApiPaging<GetTraceabDTOs>();
            var traceab = traceabmodel.GetList().Where(x => x.IsDel == false);

            var linq = from a in traceab
                       select new GetTraceabDTOs()
                       {
                           ExpirationDate=a.ExpirationDate,
                           GoodsName=a.GoodsName,
                           Id=a.Id,
                           Image=a.Image,
                           ProductionBatch=a.ProductionBatch,
                           ProductionFrim=a.ProductionFrim,
                           ProductionLicense=a.ProductionLicense,
                           CreateName=a.CreateName,
                           CreateTime=a.CreateTime,
                           UpdateName=a.UpdateName
                           
                       };

            res.totalcount = linq.Count();
            res.totalpage = (int)Math.Ceiling(res.totalcount * 1.0 / request.pagesize);
            res.pagedata = await linq.OrderByDescending(x => x.Id).Skip((request.pageindex - 1) * request.pagesize).Take(request.pagesize).ToListAsync();
            return await Task.FromResult(res);
        }
    }
}
